package com.leyou.Service;

import com.leyou.client.GoodsClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 页面静态化
 */
@Service
public class GoodHtmlService {

    @Autowired
    private Goodservice goodservice;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodHtmlService.class);

    /**
     * 生成商品详情页的详细页面
     *
     * @param spuID
     */
    public void createHtml(Long spuID) {
        PrintWriter writer = null;
        try {
            // 还是用之前写的方法获取页面数据
            Map<String, Object> spuMap = this.goodservice.LoadData(spuID);

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(spuMap);

            // 创建输出流,静态化页面的存放路径在nginx里
            File file = new File("F:\\nginx\\html\\item\\" + spuID + ".html");
            writer = new PrintWriter(file);

            // 执行页面静态化方法
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{}," + e, spuID);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化
     *
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(() -> createHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }


    /**
     * 开10个线程的工具类用来生成静态页面
     */
    public static class ThreadUtils {

        private static final ExecutorService es = Executors.newFixedThreadPool(10);

        static void execute(Runnable runnable) {
            es.submit(runnable);
        }
    }

    /**
     * 接收删除的topic，删除静态页
     *
     * @param id
     */
    public void deleteHtml(Long id) {
        File file = new File("F:\\nginx\\html\\item\\" + id + ".html");
        file.deleteOnExit();
    }
}
